#version 450

struct Line {
	vec2 start;
	vec2 end;
	vec4 color;
};

layout(set = 0, binding = 0) buffer Lines {
	Line lines[];
};

layout(set = 1, binding = 0) uniform MVP {
	mat4 model;
	mat4 view;
	mat4 proj;
	vec2 offset;
};
layout(set = 1, binding = 1) uniform LineParams {
	float thickness;
	uint lineCap;
};

layout(location = 0) out vec4 fragColor;
layout(location = 1) flat out vec2 lineStart;
layout(location = 2) flat out vec2 lineEnd;
layout(location = 3) flat out float lineHalfWidth;
layout(location = 4) flat out uint lineCapType;

uint indices[6] = { 0, 1, 2, 3, 2, 1 };

void main() {
	uint index = gl_VertexIndex / 6;
	Line line = lines[index];
	fragColor = line.color;
	lineStart = line.start;
	lineEnd = line.end;
	lineHalfWidth = thickness * 0.5;
	lineCapType = lineCap;

    vec2 lineDir = normalize(lineEnd - lineStart);
	if (lineCap > 0) {
		lineStart = lineStart - lineDir * lineHalfWidth;
		lineEnd = lineEnd + lineDir * lineHalfWidth;
	}
    vec2 normal = vec2(-lineDir.y, lineDir.x);
    vec2 halfHeight = normal * lineHalfWidth;
    vec2 squareCoords[4] = {
        lineStart - halfHeight,
        lineStart + halfHeight,
        lineEnd - halfHeight,
        lineEnd + halfHeight
    };

	lineStart += offset;
	lineEnd += offset;
	gl_Position = proj * view * model * vec4(squareCoords[indices[gl_VertexIndex % 6]], 0.0, 1.0);
}